import React, { Component } from 'react';
import {Toast} from "antd-mobile"
import {Login} from "dcloud-mobile"
import {loginServer} from "dcloud-utils"
import {httpUtil} from "dcloud-utils";
import {httpUrl} from "dcloud-core";

export default class Home extends React.Component {
    constructor(props) {
        super(props);
        this.state = {

        }
    }

    /**
     * 此页面用来替换原微商城的vauth授权, 为促销平台提供授权
     */
    componentDidMount() {
        let code = window.wxParames().code;
        let appId = window.urlParames().appid;
        let scope = window.urlParames().scope || 'snsapi_base';
        if(window.urlParames().isScope){
            scope = 'snsapi_userinfo'
        }
        let state = window.urlParames().state;
        let redirectUri;

        if (!code) {
            //第一步，没有拿到code，跳转至微信授权页面获取code
            redirectUri = this.appendParams('https://open.weixin.qq.com/connect/oauth2/authorize#wechat_redirect', {
                'appid': appId,
                //'redirect_uri': encodeURIComponent(window.location.protocol + '//' + window.location.host + '/#/login/vauth'),
                'redirect_uri': encodeURIComponent(location.href),
                'response_type': 'code',
                'scope': scope,
                'state': state,
            });
        } else {
            //第二步，从微信授权页面跳转回来，已经获取到了code，再次跳转到实际所需页面
            redirectUri = this.appendParams(window.urlParames().redirect_uri, {
                'code': code,
                'state': state
            });
        }
        // alert("redirectUri==="+redirectUri);
        location.href = redirectUri;
    }

    appendParams (url, params) {
        if (params) {
            let baseWithSearch = url.split('#')[0];
            let hash = url.split('#')[1];
            for (let key in params) {
                let attrValue = params[key];
                if (attrValue !== undefined) {
                    let newParam = key + "=" + attrValue;
                    if (baseWithSearch.indexOf('?') > 0) {
                        let oldParamReg = new RegExp('^' + key + '=[-%.!~*\'\(\)\\w]*', 'g');
                        if (oldParamReg.test(baseWithSearch)) {
                            baseWithSearch = baseWithSearch.replace(oldParamReg, newParam);
                        } else {
                            baseWithSearch += "&" + newParam;
                        }
                    } else {
                        baseWithSearch += "?" + newParam;
                    }
                }
            }

            if (hash) {
                url = baseWithSearch + '#' + hash;
            } else {
                url = baseWithSearch;
            }
        }
        // alert("url==="+url);
        return url;
    }

    render() {
        // Toast.loading('登录中~~~',0);
        return (
           <div></div>
        )
    }
}
